/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.pa.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seari.bean.pa.PaInstruct;
import com.seari.bean.pa.PaResponse;
import com.seari.pa.PaClient;
import com.seari.utils.DataUtil;

/**
 *
 * @author Rainbow
 * 
 */
public class PaClientHandler extends ChannelInboundHandlerAdapter
{
    protected static Logger logger = LoggerFactory.getLogger(PaClientHandler.class);
    // pa客户端
    PaClient client;
    
   public PaClientHandler(PaClient client)
    {
        this.client = client;
    }
    
    
    /* (non-Javadoc)
     * @see io.netty.channel.ChannelInboundHandlerAdapter#channelRead(io.netty.channel.ChannelHandlerContext, java.lang.Object)
     * 读取消息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
    	
        //ByteBuf result = (ByteBuf) msg;  
        byte[] result1 = (byte[]) msg;  
        //logger.info(DataUtil.BytesToHexStr(result1));
        if(result1[0] == (byte)0xEB && result1[1] == (byte)0x90)
        {
            PaInstruct paInstruct = new PaInstruct();
            paInstruct.boxNum = result1[2];
            paInstruct.body = new byte[result1.length - 4];
            for(int i = 3;i < result1.length - 1;i++)
            {
                paInstruct.body[i-3] = result1[i];
            }
            paInstruct.chk = result1[result1.length - 1];
            
            if(!checkCHK(paInstruct))
            {
                //do nothing
            }else{
                handleRequest(paInstruct);
            }
            
        }
        else
        {
            logger.warn("frame illegal :" + DataUtil.BytesToHexStr(result1));
        }
        //logger.info("Server said:" + DataUtil.BytesToHexStr(result1));   
    }

    /* (non-Javadoc)
     * @see io.netty.channel.ChannelInboundHandlerAdapter#channelActive(io.netty.channel.ChannelHandlerContext)
     * 
     * 客户端去和服务端连接成功时触发channelActive
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        System.out.println("channel active");
//        String msg = "测试成功?";  
//        ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());  
//        encoded.writeBytes(msg.getBytes());  
//        ctx.write(encoded);  
//        ctx.flush();  
    }
    
    public boolean checkCHK(PaInstruct paInstruct)
    {
        byte check[] = new byte[paInstruct.body.length + 1];
        for(int i = 0;i < paInstruct.body.length;i++)
        {
            check[i] = paInstruct.body[i];
        }
        check[check.length - 1] = paInstruct.boxNum;
        int chk = DataUtil.SumChkInt(check);
        return (byte)chk == paInstruct.chk;
    }
    
    public void handleRequest(PaInstruct paInstruct )
    {
        //System.out.println(new Date().toString()+paInstruct.toString());
    	System.out.println(client.toString()+" "+client.responseList.size());
        if(client.responseList.size() > 0)
        {
            PaResponse paResponse = client.responseList.remove(0);
            try
            {
                client.sendPaFrame(paResponse);
                if(client.getTimer() == null)
                {
                    PaTimer timer = new PaTimer();
                    client.setTimer(timer);
                    timer.setClient(client);
                    timer.refreshTimer();
                    Thread thread = new Thread(timer);
                    thread.start();
                }else{
                    //发送开启指令后重新刷新计时器
                    PaTimer timer = client.getTimer();
                    timer.refreshTimer();
                }
            } catch (Exception ex)
            {
                logger.warn(ex.getMessage());
            }
        }else if(client.stopResponseList.size() > 0){
            PaResponse paResponse = client.stopResponseList.remove(0);
            try
            {
                client.sendPaFrame(paResponse);
            } catch (Exception ex)
            {
                logger.warn("send stop frame error:" + ex.getMessage());
            }
        }else{
            client.sendNoAnswerFrame();
        }
    }
    
    
        
}
